package csu.web.mypetstore.persistence.impl;

import csu.web.mypetstore.domain.Sequence;
import csu.web.mypetstore.persistence.DBUtil;
import csu.web.mypetstore.persistence.SequenceDao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class SequenceDaoImpl implements SequenceDao {

    private static final String getSequence = "SELECT name, nextid FROM SEQUENCE WHERE NAME = ?";
    private static final String upDateSequence = "UPDATE SEQUENCE SET NEXTID = ? WHERE NAME = ?";

    @Override
    public Sequence getSequence(String name) {
        Sequence sequence = new Sequence();
        Connection connection = DBUtil.getConnection();
        try {
            PreparedStatement preparedStatement = connection.prepareStatement(getSequence);
            preparedStatement.setString(1,name);
            ResultSet resultSet = preparedStatement.executeQuery();
            if(resultSet.next()){
                sequence.setName(resultSet.getString("name"));
                sequence.setNextId(resultSet.getInt("nextid"));
            }
            DBUtil.closeResultSet(resultSet);
            DBUtil.closeConnection(connection);
            DBUtil.closeStatement(preparedStatement);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        return sequence;
    }

    @Override
    public void updateSequence(Sequence sequence) {
        Connection connection = DBUtil.getConnection();
        try {
            PreparedStatement preparedStatement = connection.prepareStatement(upDateSequence);
            preparedStatement.setInt(1,sequence.getNextId());
            preparedStatement.setString(2,sequence.getName());

            int isSucceed = preparedStatement.executeUpdate();
            if(isSucceed>0){
                System.out.println("sequenceUpdated!");
            }else {
                System.out.println("sequenceFailed!");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
